package com.by_man.presenter.module_health_management.health_reminder;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.main_page.MainActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 健康提醒activity
 * Created by man on 2017-02-21.
 */
public class HealthReminderActivity extends AppCompatActivity {
    // 记录所有的任务id
    public static Set<Integer> TaskIDs;

    // 存放所有任务信息
    private ArrayList<TaskInfo> taskInfos = new ArrayList<>();

    // 在listview中创建view
    private LayoutInflater inflater = null;

    // 存储checkboxUI对象
    private Map<Object, Integer> objectMap = new HashMap<Object, Integer>();

    private AlarmManager alarmManager;
    private int oldPostion = -1;
    private int indexPosition=0;
    private static int ResetItemId = -1;
    private static int ResetItemTaskId = -1;
    private String[] weekday=new String[]{"周一","周二","周三","周四","周五","周六","周日"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_reminder);
        //((SharedApplication) getApplication()).addActivity(this);
        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_health_reminder, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Intent intent = new Intent(this, MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
                break;
            case R.id.add_alarm:
                Intent intent_B = new Intent(this, HealthAlarmActivity.class);
//                intent_B.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent_B);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, MainActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode,event);
//    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        // 初始化，取出所有的任务信息
        initAlarmTaskInfos();

        // 这几句意图不明显
        Intent intent= getIntent();
        if (intent.getStringExtra("close")=="true")
            Toast.makeText(this,"aaaaaaaaaaaaaaa",Toast.LENGTH_SHORT).show();

        Bundle bundle = this.getIntent().getExtras();
        alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);

        // 取出新的任务信息
        if (bundle!=null) {
            // TODO: 2016/4/8 当没有重复的提醒回来时可能会崩溃
            String tag=bundle.getString("tag");
            Boolean vibration =bundle.getBoolean("vibration");
            int taskId = bundle.getInt("taskId");
            String time = bundle.getString("time");
            Boolean repeat = bundle.getBoolean("repeat");
            String weekday = bundle.getString("weekday");
            boolean reset = bundle.getBoolean("reset");


            TaskInfo data = new TaskInfo();
            data.taskId=taskId;
            data.time = time;
            data.isEnable=true;
            data.isVibration=vibration;
            data.isRepeat=repeat;
            data.tag=tag;
            data.reset = reset;

            Iterator j = TaskIDs.iterator();//先迭代出来

            while(j.hasNext()){//遍历
                Log.e("taskids--->", j.next()+"");
            }

            if(reset) {
                deleteData(ResetItemTaskId);
                taskInfos.remove(ResetItemId);
            }

            if (data.isRepeat) {
                Integer[] tempSelected = new Integer[]{0,0,0,0,0,0,0};
                String[] tempWeekday = weekday.split(" ");
                for (int i = 0; i < 7; i++) {
                    tempSelected[i] = Integer.parseInt(tempWeekday[i]);
                }
                data.selected = tempSelected;
            }
            taskInfos.add(data);
            setAlarmData(data);             // 将此任务信息存到本地
        }

        // 对ui组件进行相关的设定
        final ListView list = (ListView) findViewById(R.id.list_view);
        inflater = LayoutInflater.from(this);
        final ListViewAdapter adapter = new ListViewAdapter();
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                TaskInfo data = taskInfos.get(position);

                if (oldPostion == position) {
//                    if (data.expand) {
//                        oldPostion = -1;
//                    }
                    data.expand = !data.expand;
//                    data.expand=false;
                } else {
                    if (oldPostion != -1 && oldPostion < taskInfos.size()) {
                        taskInfos.get(oldPostion).expand = false;
                    }
                    oldPostion = position;
                    data.expand = true;
                }

                int totalHeight = 0;
                indexPosition = oldPostion;
                for (int i = 0; i < adapter.getCount(); i++) {

                    Log.e("max--i-->", adapter.getCount() + "");

                    View viewItem = adapter.getView(i, null, list);//这个很重要，那个展开的item的measureHeight比其他的大
                    viewItem.setLayoutParams(new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                    viewItem.measure(0,0);
                    totalHeight += viewItem.getMeasuredHeight();
                }

                ViewGroup.LayoutParams params = list.getLayoutParams();
                params.height = totalHeight
                        + (list.getDividerHeight() * (list.getCount() - 1));
                list.setLayoutParams(params);

                adapter.notifyDataSetChanged();
            }
        });
    }

    // 将存储的tasks信息取出
    private void initAlarmTaskInfos() {
        if (null == TaskIDs) {
            TaskIDs = new HashSet<Integer>();
        }
        SharedPreferences sp = this.getSharedPreferences("metaAlarm", MODE_PRIVATE);
        initTaskIDs(sp.getString("taskIds", ""));
        for (int taskId : TaskIDs) {
            String data = sp.getString(Integer.toString(taskId),"");
            Log.i("TaskInfo", data);
            if (data.length()!=0){
                String[] datas=data.split("!!!");
                TaskInfo mydata=new TaskInfo();
                mydata.taskId=taskId;
                mydata.time = datas[0];
                mydata.isEnable=Boolean.parseBoolean(datas[1]);
                mydata.isVibration=Boolean.parseBoolean(datas[2]);
                mydata.isRepeat=Boolean.parseBoolean(datas[3]);
                mydata.tag=datas[4];
                if (mydata.isRepeat) {
                    Integer[] tempSelected = new Integer[]{0,0,0,0,0,0,0};
                    String[] tempWeekday = datas[5].split(" ");
                    for (int i = 0; i < 7; i++) {
                        tempSelected[i] = Integer.parseInt(tempWeekday[i]);
                    }
                    mydata.selected = tempSelected;
                }
                taskInfos.add(mydata);
            }
        }
    }

    // 将字符串taskids信息转换为集合TaskIDs
    private void initTaskIDs(String taskIdStr) {
        Log.i("TaskIds", taskIdStr);
        String[] taskIdsArray= taskIdStr.split(" ");
        for (String temp:taskIdsArray){
            if (temp.trim().length()!=0){
                TaskIDs.add(Integer.parseInt(temp));
            }
        }
    }

    // 删除本地数据中的相应id的任务
    private void deleteData(int taskId) {
        SharedPreferences sp = this.getSharedPreferences("metaAlarm", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        String temp=sp.getString(Integer.toString(taskId),"");
        Log.d("TaskId",Integer.toString(taskId));
        Log.d("TaskInfo","---->"+temp);

        if (temp.length()!=0)
            for (String tempId:temp.split("!!!")[5].split(" ")){
                // TODO: 2016/4/11 删除任务
                Intent I = new Intent(getApplicationContext(), AlarmReceiver.class);
                PendingIntent pendIntent = PendingIntent.getBroadcast(getApplicationContext(), Integer.parseInt(tempId), I, PendingIntent.FLAG_CANCEL_CURRENT);
                alarmManager.cancel(pendIntent);
                pendIntent.cancel();
            }
        editor.remove(Integer.toString(taskId));
        TaskIDs.remove(taskId);
        editor.putString("taskIds", set2String(TaskIDs));
        editor.commit();
    }

    // 将集合对象TaskIDs中的id信息转化为字符串形式
    private String set2String(Set<Integer> sets) {
        Log.d("Set", sets.toString());
        if (sets.size()==0)
            return "";
        String result="";
        for (int temp:sets){
            result=result+" "+Integer.toString(temp);
        }
        Log.d("StrOfSet", result);
        return  result.substring(1);
    }

    // 将任务信息存到本地
    // 格式为:time!!!enable!!!vibration!!!repeat!!!tag!!!weekdays
    private void setAlarmData(TaskInfo data) {
        SharedPreferences sp = this.getSharedPreferences("metaAlarm", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        String selected="0 0 0 0 0 0 0";
        if (data.isRepeat){
            selected="";
            for (int temp:data.selected){
                selected=selected+" "+Integer.toString(temp);
            }
            selected=selected.substring(1);
        }
        String result=data.time+"!!!"+Boolean.toString(data.isEnable)+"!!!"+Boolean.toString(data.isVibration)+
                "!!!" + Boolean.toString(data.isRepeat) + "!!!"+data.tag+"!!!"+selected;
        editor.putString(Integer.toString(data.taskId),result);

        TaskIDs.add(data.taskId);
        editor.putString("taskIds",set2String(TaskIDs));
        editor.commit();
    }

    // 这个类封装闹钟任务信息
    private class TaskInfo {
        int taskId;
        boolean expand;
        String time;
        String tag;
        boolean isEnable;
        boolean isVibration;
        boolean isRepeat;
        Integer[] selected = new Integer[] {0,0,0,0,0,0,0};
        boolean reset = false;
    }

    // 自定义的listview的adapter
    private class ListViewAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return taskInfos.size();
        }

        @Override
        public Object getItem(int position) {
            return taskInfos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ListViewItemUIs tag = new ListViewItemUIs();
            TaskInfo data = taskInfos.get(position);
//            indexPosition=position;
            if(convertView == null) {
                convertView = inflater.inflate(R.layout.health_reminder_listview_item, null);
                tag.item1 = (TextView)convertView.findViewById(R.id.item1);
                tag.itemText=(TextView)convertView.findViewById(R.id.itemText);
                tag.item2 = (RelativeLayout)convertView.findViewById(R.id.item2);
                tag.switchEnable=(Switch)convertView.findViewById(R.id.switchEnable);
                tag.checkBoxRepeat=(CheckBox)convertView.findViewById(R.id.checkBoxRepeat);
                tag.checkBoxVibration=(CheckBox)convertView.findViewById(R.id.checkBoxVibration);
                tag.buttonDel=(Button)convertView.findViewById(R.id.buttonDel);
                tag.buttonReset=(Button)convertView.findViewById(R.id.buttonReset);
                tag.weekdayText=(TextView)convertView.findViewById(R.id.textView3);
                objectMap.put(tag.checkBoxRepeat,position);
                convertView.setTag(tag);
            }else{
                tag = (ListViewItemUIs) convertView.getTag();
            }
            if(data.expand) {
                tag.item2.setVisibility(View.VISIBLE);
            }else{
                tag.item2.setVisibility(View.GONE);
            }
//            tag.spinnerTag.set
            tag.item1.setText(data.time);
            tag.itemText.setText(data.tag);
            tag.switchEnable.setChecked(data.isEnable);
            tag.switchEnable.getThumbDrawable().setColorFilter(data.isEnable ? Color.BLUE : Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
            tag.switchEnable.getTrackDrawable().setColorFilter(data.isEnable ? Color.BLUE : Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
            tag.switchEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                    Switch tempSwitch = (Switch) compoundButton;
                    tempSwitch.getThumbDrawable().setColorFilter(checked ? Color.BLUE : Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
                    tempSwitch.getTrackDrawable().setColorFilter(checked ? Color.BLUE : Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
                }
            });


            tag.checkBoxRepeat.setChecked(data.isRepeat);
            tag.checkBoxVibration.setChecked(data.isVibration);

            tag.checkBoxRepeat.setClickable(false);
            tag.checkBoxRepeat.setEnabled(false);

            tag.checkBoxVibration.setClickable(false);
            tag.checkBoxVibration.setEnabled(false);

            if (data.isRepeat){
                String tempWeekday="";
                for (int i=0;i<7;i++){
                    if (data.selected[i]!=0){
                        tempWeekday=tempWeekday+" "+weekday[i];
                    }
                }
                tag.weekdayText.setText(tempWeekday.substring(1));
            }else
                tag.weekdayText.setText("不重复");
            tag.buttonDel.setOnClickListener(new Button.OnClickListener(){
                @Override
                public void onClick(View v) {
                    int taskid=taskInfos.get(indexPosition).taskId;
                    deleteData(taskid);
                    taskInfos.remove(indexPosition);
                    //list.setAdapter(myAdapter);
                    ListViewAdapter.this.notifyDataSetChanged();
                }
            });
            tag.buttonReset.setOnClickListener(new Button.OnClickListener(){
                @Override
                public void onClick(View v) {
                    int taskid=taskInfos.get(indexPosition).taskId;


                    /*deleteData(taskid);
                    myList.remove(indexPosition);
                    list.setAdapter(myAdapter);*/

                    ResetItemId = indexPosition;
                    ResetItemTaskId = taskid;
                    Log.e("修改内容","ResetItemId-->"+ResetItemId+"++++"+"ResetItemTaskId--->"+ResetItemTaskId);
                    Intent intent = new Intent(HealthReminderActivity.this, HealthAlarmActivity.class);
                    intent.putExtra("reset", true);
                    intent.putExtra("taskId", taskid);

                    // 删除之前的
                    deleteData(taskid);
                    startActivity(intent);
                }
            });
            return convertView;
        }
    }

    // 这个类将listview的每项中的ui组件封装到一起
    private class ListViewItemUIs {
        private TextView item1;
        private TextView itemText;
        private TextView weekdayText;
        private ListPopupWindow lpw;
        private String[] list;

        private Switch switchEnable;
        private RelativeLayout item2;
        private CheckBox checkBoxVibration;
        private CheckBox checkBoxRepeat;
        private Button buttonDel;
        private Button buttonReset;
    }

//    protected void onRestart()
//    {
//        super.onRestart();
//        Intent intent=new Intent(this,GestureLockActivity.class);
//        intent.putExtra("class",this.getClass().getName());
//        intent.putExtra("position", 0);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
//    }
}
